const express = require('express');
const router = express.Router();
const multer = require("multer");
const path = require("path");
const db = require("../model/db");

// 作者：伍文彬
// 添加
router.post("/", async (req, res) => {
    const data = await db.Article.create(req.body);
    res.send(data);
})

// 作者：伍文彬
router.put("/:id", async (req, res) => {
            await db.Article.updateOne({
                _id: db.ObjectId(req.params.id)
            }, req.body); //(要修改的对象)
             res.send(true);
})

// 作者：伍文彬
// 删除文章
router.delete("/:id", async (req, res) => {
    await db.Article.deleteOne({
        _id: req.params.id
    });
    res.send(true);
})

// 作者：伍文彬
// 得到所有文章
router.get("/", async (req, res) => {
    const page = parseInt(req.query.page);
    const limit = parseInt(req.query.limit);
    let contion = {}; //条件对象
    if (req.query.key) {
        contion = {
            name: req.query.key.toUpperCase()
        }
    }
    let condition = {};
    if (req.query.key) {
        const exp = new RegExp(req.query.key, "i");
        condition = {
            $or: [{
                    title: {
                        $regex: exp
                    }
                },
                {
                    content: {
                        $regex: exp
                    }
                },
                {
                    description: {
                        $regex: exp
                    }
                }
            ]
        };
    }
    const data = await db.Article.find(condition).skip((page - 1) * limit).limit(limit);
    const count = await db.Article.count(condition);
    res.send({
        "code": 0,
        "msg": "",
        "count": count,
        "data": data
    });
})


// 作者：伍文彬
// 得到单个文章：修改时需要用
router.get("/:id",async (req,res)=>{
    const data = await db.Article.findById(req.params.id);
    res.send(data);
})



module.exports = router;